/**
 * 服务端响应解析测试
 * 
 * 用途：测试TabletBrainWaveResponse模型的JSON解析功能
 * 方法：使用实际的服务端响应格式进行解析测试
 * 原理：验证新的响应模型能正确解析服务端返回的JSON数据，避免NullPointerException
 */
package com.example.brain_wave.test

import com.example.brain_wave.api.model.TabletBrainWaveResponse
import com.example.brain_wave.api.model.FrequencyBands
import com.google.gson.Gson
import org.junit.Test
import org.junit.Assert.*

class ResponseParsingTest {
    
    private val gson = Gson()
    
    @Test
    fun testParseCompleteResponse() {
        // 使用用户提供的实际服务端响应格式
        val jsonResponse = """
        {
            "success": true,
            "message": "数据分析完成",
            "session_id": "410",
            "timestamp": 1729851723000,
            "received_data_points": 256,
            "sleep_stage": "light_sleep",
            "confidence": 0.546,
            "frequency_bands": {
                "Delta": 0.3890119825634894,
                "Theta": 0.3416494119162977,
                "Alpha": 0.10664366044997299,
                "Sigma": 0.0406619774698585,
                "Beta": 0.07434964388057909,
                "Gamma": 0.03776730498867424
            },
            "analysis_duration_ms": 1250,
            "buffer_size": 16809,
            "yasa_available": true
        }
        """.trimIndent()
        
        // 解析响应
        val response = gson.fromJson(jsonResponse, TabletBrainWaveResponse::class.java)
        
        // 验证基本字段
        assertNotNull(response)
        assertTrue(response.success)
        assertEquals("数据分析完成", response.message)
        assertEquals("410", response.sessionId)
        assertEquals(1729851723000L, response.timestamp)
        assertEquals(256, response.receivedDataPoints)
        
        // 验证分析结果字段
        assertEquals("light_sleep", response.sleepStage)
        assertEquals(0.546f, response.confidence, 0.001f)
        
        // 验证频域数据
        assertNotNull(response.frequencyBands)
        val bands = response.frequencyBands!!
        assertEquals(0.3890119825634894f, bands.delta, 0.0001f)
        assertEquals(0.3416494119162977f, bands.theta, 0.0001f)
        assertEquals(0.10664366044997299f, bands.alpha, 0.0001f)
        assertEquals(0.0406619774698585f, bands.sigma, 0.0001f)
        assertEquals(0.07434964388057909f, bands.beta, 0.0001f)
        assertEquals(0.03776730498867424f, bands.gamma, 0.0001f)
        
        // 验证性能指标字段
        assertEquals(1250, response.analysisDurationMs)
        assertEquals(16809, response.bufferSize)
        assertTrue(response.yasaAvailable)
    }
    
    @Test
    fun testParseMinimalResponse() {
        // 测试只包含必需字段的响应
        val jsonResponse = """
        {
            "success": true,
            "message": "数据分析完成",
            "session_id": "411",
            "timestamp": 1729851724000,
            "received_data_points": 128,
            "buffer_size": 8404,
            "yasa_available": true
        }
        """.trimIndent()
        
        // 解析响应
        val response = gson.fromJson(jsonResponse, TabletBrainWaveResponse::class.java)
        
        // 验证基本字段
        assertNotNull(response)
        assertTrue(response.success)
        assertEquals("数据分析完成", response.message)
        assertEquals("411", response.sessionId)
        assertEquals(1729851724000L, response.timestamp)
        assertEquals(128, response.receivedDataPoints)
        assertEquals(8404, response.bufferSize)
        assertTrue(response.yasaAvailable)
        
        // 验证可选字段为null（不应该引起NullPointerException）
        assertNull(response.sleepStage)
        assertNull(response.confidence)
        assertNull(response.frequencyBands)
        assertNull(response.analysisDurationMs)
    }
    
    @Test
    fun testParseFailureResponse() {
        // 测试失败响应
        val jsonResponse = """
        {
            "success": false,
            "message": "数据分析失败",
            "session_id": "412",
            "timestamp": 1729851725000,
            "received_data_points": 0,
            "buffer_size": 0,
            "yasa_available": false
        }
        """.trimIndent()
        
        // 解析响应
        val response = gson.fromJson(jsonResponse, TabletBrainWaveResponse::class.java)
        
        // 验证失败响应
        assertNotNull(response)
        assertFalse(response.success)
        assertEquals("数据分析失败", response.message)
        assertEquals("412", response.sessionId)
        assertEquals(0, response.receivedDataPoints)
        assertEquals(0, response.bufferSize)
        assertFalse(response.yasaAvailable)
    }
    
    @Test
    fun testNoNullPointerException() {
        // 测试各种边界情况，确保不会出现NullPointerException
        val responses = listOf(
            // 空的frequency_bands对象
            """{"success": true, "message": "test", "session_id": "1", "timestamp": 1000, "received_data_points": 100, "buffer_size": 1000, "yasa_available": true, "frequency_bands": {}}""",
            
            // 缺少某些frequency_bands字段
            """{"success": true, "message": "test", "session_id": "2", "timestamp": 2000, "received_data_points": 100, "buffer_size": 1000, "yasa_available": true, "frequency_bands": {"Delta": 0.5}}""",
            
            // null值
            """{"success": true, "message": "test", "session_id": "3", "timestamp": 3000, "received_data_points": 100, "buffer_size": 1000, "yasa_available": true, "sleep_stage": null, "confidence": null}"""
        )
        
        responses.forEach { jsonResponse ->
            try {
                val response = gson.fromJson(jsonResponse, TabletBrainWaveResponse::class.java)
                assertNotNull("响应解析不应该返回null", response)
                
                // 验证基本字段存在
                assertTrue("success字段应该存在", response.success)
                assertNotNull("message字段应该存在", response.message)
                assertNotNull("sessionId字段应该存在", response.sessionId)
                assertTrue("timestamp应该大于0", response.timestamp > 0)
                
            } catch (e: NullPointerException) {
                fail("解析响应时不应该出现NullPointerException: ${e.message}")
            } catch (e: Exception) {
                // 其他异常可以接受，但不应该是NullPointerException
                assertFalse("不应该出现NullPointerException", e is NullPointerException)
            }
        }
    }
}